/**
 * Game 游戏逻辑编写
 */
(function (window, undefined) {

    let that;

    function Game(map, options) {
        this.map = map;
        that = this;
        this.food = new Food(map, options);
        this.snake = new Snake(map, options);
    }
    /**
     * 开始游戏
     */
    Game.prototype.start = function () {
        //渲染食物
        this.food.render();
        this.food.render();

        //渲染蛇
        this.snake.render();

        //蛇运动和吃食物
        run();
        //按键逻辑
        bindKey();
    }

    /**
     * 让蛇跑起来
     */
    function run() {
        const timer = setInterval(() => {
            //蛇移动
            that.snake.move();
            //计算是否达到边界 根据份数计算
            const maxLeft = that.map.offsetWidth / that.snake.width;
            const maxTop = that.map.offsetWidth / that.snake.height;
            const header = that.snake.body[0];//蛇头

            //判断蛇头是否吃到了食物,食物都存储到了elements中
            let headX = header.x * that.snake.width;
            let headY = header.y * that.snake.height;
            const len = that.food.elements.length;
            for (let i = 0; i < len; i++) {
                const food = that.food.elements[i];
                //判断蛇头是否和食物坐标相同
                if (headX === food.offsetLeft && headY === food.offsetTop) {
                    //删除食物 随机生成
                    that.food.remove(i)
                    that.food.render();
                    //蛇身增加一节
                    const last = that.snake.body[that.snake.body.length - 1];//增加的和最后一节相同 下次渲染会进行增长
                    that.snake.body.push({
                        x: last.x,
                        y: last.y,
                        color: last.color
                    });
                }
            }

            //判断蛇头是否达到边界
            if (header.x >= maxLeft || header.x < 0 || header.y >= maxTop || header.y < 0) {
                clearInterval(timer);
                alert("Game Over");
            }
        }, 150);
    }

    //封装按键逻辑代码
    function bindKey() {
        document.onkeydown = function (ev) {
            //判断按键 37---left   38---top   39---right  40---bottom
            console.log(ev.key);
            switch (ev.key) {
                case "ArrowLeft":
                    that.snake.direction = "left";
                    break;
                case "ArrowUp":
                    that.snake.direction = "top";
                    break;
                case "ArrowRight":
                    that.snake.direction = "right";
                    break;
                case "ArrowDown":
                    that.snake.direction = "bottom";
                    break;
            }
        }
    }

    window.Game = Game;
})(window, undefined);

const map = document.getElementById("map");
const game = new Game(map);
game.start();